package com.lu.netty.impl

import androidx.annotation.IntRange
import com.lu.netty.data.DataType
import com.lu.netty.data.NettyMessageVo
import com.lu.netty.io.core.NettyConnector
import com.lu.netty.io.core.NettyLog
import com.lu.netty.io.dispatcher.INettyServerListener
import com.lu.netty.io.server.ANettyServer

/**
 * FileName : BaseNettyServer
 * Author : luqihua
 * Date : 2024/12/18
 * Desc :
 **/

class BaseNettyServer(
    @IntRange(from = 1000, to = 65535)
    port: Int,
) : ANettyServer(port) {
    companion object {
        private const val TAG = "BaseNettyServer"
    }

    private var listener: INettyServerListener? = null

    override fun onMessageArrived(connector: NettyConnector, message: String) {
        try {
            val messageVo = NettyMessageVo.fromJson(message) ?: return
            when (messageVo.dataType) {
                DataType.HEARTBEAT -> {
                    val response = listener?.onHeartbeat(connector, messageVo) ?: ""
                    connector.send(NettyMessageVo.createHeartbeat(response).toJson())
                }

                else -> listener?.onContent(connector, messageVo)
            }
        } catch (e: Exception) {
            NettyLog.e(TAG, "onMessageArrived : ", e)
        }
    }

    override fun onClientChange(connector: NettyConnector, isAccept: Boolean) {
        listener?.onClientChange(connector, isAccept)
    }

    fun setListener(listener: INettyServerListener) {
        this.listener = listener
    }


    override fun sendAll(message: String) {
        val messageVo = NettyMessageVo(dataType = DataType.CONTENT, message = message)
        super.sendAll(messageVo.toJson())
    }
}